package com.qst.service.impl;

import com.qst.pojo.entity.Station;
import com.qst.pojo.entity.SystemSettings;
import com.qst.repository.StationRepository;
import com.qst.repository.SystemSettingsRepository;
import com.qst.service.InventoryMonitorService;
import com.qst.service.NotificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 库存监控服务实现类
 */
@Service
public class InventoryMonitorServiceImpl implements InventoryMonitorService {

    private static final Logger logger = LoggerFactory.getLogger(InventoryMonitorServiceImpl.class);

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private SystemSettingsRepository settingsRepository;

    @Autowired
    private NotificationService notificationService;

    /**
     * 用于记录已发送警告的站点，避免重复发送
     * Key: stationId-alertType, Value: lastAlertTime
     */
    private Map<String, Long> alertHistory = new HashMap<>();

    /**
     * 警告发送间隔（毫秒），避免频繁发送，默认1小时
     */
    private static final long ALERT_INTERVAL = 60 * 60 * 1000;

    @Override
    public void checkAllStationsInventory() {
        try {

            // 获取库存配置
            int lowStockThreshold = Integer.parseInt(getSettingValue("inventory.lowStockThreshold", "100"));
            int fullStockThreshold = Integer.parseInt(getSettingValue("inventory.fullStockThreshold", "2000"));
            boolean emailAlertsEnabled = Boolean.parseBoolean(getSettingValue("inventory.emailAlerts", "true"));

            if (!emailAlertsEnabled) {
                return;
            }

            // 获取所有活跃的站点
            List<Station> stations = stationRepository.findAll();

            for (Station station : stations) {
                // 只检查活跃和繁忙状态的站点
                if (station.getStatus() == Station.StationStatus.closed) {
                    continue;
                }
                
                // 检查低库存
                if (station.getCurrentLoad() <= lowStockThreshold) {
                    if (shouldSendAlert(station.getId(), "low")) {
                        notificationService.sendLowStockAlert(station, lowStockThreshold);
                        recordAlert(station.getId(), "low");
                    }
                }
                
                // 检查满载库存
                if (station.getCurrentLoad() >= fullStockThreshold) {
                    if (shouldSendAlert(station.getId(), "full")) {
                        notificationService.sendFullStockAlert(station, fullStockThreshold);
                        recordAlert(station.getId(), "full");
                    }
                }
            }

        } catch (Exception e) {
            logger.error("检查站点库存失败", e);
        }
    }

    @Override
    public void checkStationInventory(Integer stationId) {
        try {
            Optional<Station> stationOpt = stationRepository.findById(stationId);
            if (!stationOpt.isPresent()) {
                return;
            }

            Station station = stationOpt.get();
            
            // 获取库存配置
            int lowStockThreshold = Integer.parseInt(getSettingValue("inventory.lowStockThreshold", "100"));
            int fullStockThreshold = Integer.parseInt(getSettingValue("inventory.fullStockThreshold", "2000"));
            boolean emailAlertsEnabled = Boolean.parseBoolean(getSettingValue("inventory.emailAlerts", "true"));

            if (!emailAlertsEnabled) {
                return;
            }

            // 检查低库存
            if (station.getCurrentLoad() <= lowStockThreshold) {
                notificationService.sendLowStockAlert(station, lowStockThreshold);
            }
            
            // 检查满载库存
            if (station.getCurrentLoad() >= fullStockThreshold) {
                notificationService.sendFullStockAlert(station, fullStockThreshold);
            }

        } catch (Exception e) {
            logger.error("检查站点 {} 库存失败", stationId, e);
        }
    }

    /**
     * 判断是否应该发送警告（避免频繁发送）
     */
    private boolean shouldSendAlert(Integer stationId, String alertType) {
        String key = stationId + "-" + alertType;
        Long lastAlertTime = alertHistory.get(key);
        
        if (lastAlertTime == null) {
            return true;
        }
        
        long currentTime = System.currentTimeMillis();
        return (currentTime - lastAlertTime) >= ALERT_INTERVAL;
    }

    /**
     * 记录警告发送时间
     */
    private void recordAlert(Integer stationId, String alertType) {
        String key = stationId + "-" + alertType;
        alertHistory.put(key, System.currentTimeMillis());
    }

    /**
     * 从数据库获取配置值
     */
    private String getSettingValue(String key, String defaultValue) {
        Optional<SystemSettings> setting = settingsRepository.findBySettingKey(key);
        return setting.map(SystemSettings::getSettingValue).orElse(defaultValue);
    }
}

